package com.huixuebao.insure.controller;

import com.alibaba.fastjson.JSONObject;
import com.fasterxml.jackson.core.type.TypeReference;
import com.huixuebao.common.bean.ResponseData;
import com.huixuebao.common.util.AESEncrypt;
import com.huixuebao.common.util.JsonUtil;
import com.huixuebao.common.util.RSAEncrypt;
import com.huixuebao.common.util.RSASign;
import com.huixuebao.insure.common.config.GlobalConfig;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

/**
 * 工具接口
 *
 * @author yufatao
 * @version 1.0
 * @date 2020-11-03 19:57
 */
@Slf4j
@RestController
@RequestMapping("/tool")
public class ToolController {

    @Autowired
    GlobalConfig globalConfig;

    /**
     * 生成签名公私钥
     * @author yufatao
     * @date 2020-11-03 20:02
     * @param []
     * @return java.util.Map<java.lang.String,java.lang.String>
     */
    @GetMapping("/generateSignKey")
    public Map<String, String> generateSignSecretKey() throws NoSuchAlgorithmException {
        return RSAEncrypt.genKeyPair();
    }

    /**
     * 生成数据加解密秘钥
     * @author yufatao
     * @date 2020-11-03 20:08
     * @param []
     * @return java.lang.String
     */
    @GetMapping("/generateDataSecretKey")
    public String generateDataSecretKey() throws NoSuchAlgorithmException {
        return AESEncrypt.keyRandomGenerate();
    }

    /**
     * 加密数据
     * @author yufatao
     * @date 2020-11-03 20:14
     * @param [data]
     * @return java.lang.String
     */
    @PostMapping("/encryptData")
    public Map<String, String> encryptData(@RequestBody JSONObject data) {
        Map<String, String> result = new HashMap<>();
        String content = data.toJSONString();
        result.put("rawData", content);
        result.put("encryptedData", AESEncrypt.encrypt(data.toJSONString(), globalConfig.getDataKey()));
        return result;
    }

    /**
     * 解密数据
     * @author yufatao
     * @date 2020-11-03 20:14
     * @param
     * @return java.lang.String
     */
    @PostMapping("/decryptData")
    public String decryptData(String data) {
        return AESEncrypt.decrypt(data, globalConfig.getDataKey());
    }

    /**
     * TODO 暂时不可用
     * @author yufatao
     * @date 2020-11-03 21:16
     * @param [data]
     * @return java.lang.Boolean
     */
    @PostMapping("/signVerify")
    public Boolean signVerify(String data) throws Exception {
        ResponseData responseData = JsonUtil.getObjectData(AESEncrypt.decrypt(data, globalConfig.getDataKey()), new TypeReference<ResponseData>() {
        });

        return RSASign.verifyWhenSha1Sign(responseData.getData(), responseData.getSign(), globalConfig.getPublicKey());
    }

}